<?php

namespace app\common\model;

use app\admin\controller\Member;
use app\admin\model\Config;
use think\cache\driver\Redis;
use think\Db;
use think\Exception;
use think\Model;

/**
 * 邮箱验证码
 */
class FishLoc extends Model
{

    protected $autoWriteTimestamp = true;
    protected $updateTime = 'update_time';
    protected $createTime = 'create_time';

    protected $table = 'yzn_fish_loc';

    protected $expireTime = 24 * 60 * 60;

    public function __construct()
    {
//        $this->redis = (new Redis(config('token.redis')));
    }

    public function user()
    {
        return $this->belongsTo(MemberModel::class, 'uid', 'id')->setEagerlyType(0);
    }


    public function addLoc($param)
    {
        try {
            if (!$param['loc_name'] || !$param['longitude'] || !$param['latitude'] || !$param['address']) {
                throw new Exception('缺少参数');
            }
            $loc = self::where(['latitude' => $param['latitude'], 'longitude' => $param['longitude']])->find();
            if ($loc) {
                throw new Exception('地点已经存在');
            }
            if (!self::allowField(['uid', 'loc_name', 'longitude', 'latitude', 'address'])->save($param)) {
                throw new Exception('添加失败，请重新尝试');
            }
            return ['code' => 200, 'msg' => '上传成功', 'data' => ''];
        } catch (Exception $e) {
            return ['code' => 201, 'msg' => $e->getMessage()];
        }
    }


    public function getLocList($param)
    {
        $map = [];
        $map['yzn_fish_loc.status'] = 1;
        $array = $this->getAround($param['longitude'], $param['latitude'], 100000);
        $list = self::with('user')
            ->where($map)
            ->whereBetween('longitude', [$array['minLng'], $array['maxLng']])
            ->whereBetween('latitude', [$array['minLat'], $array['maxLat']])
            ->field('uid,loc_name,longitude,latitude,address')
            ->order('create_time desc')
            ->select();
        return ['code' => 200, 'msg' => '获取成功', 'data' => $list];
    }


    public function getUserLocList($param)
    {
        $map = [];
        $map['yzn_fish_loc.status'] = 1;
        $map['uid'] = $param['uid'];
        $page = $param['page'] ?? 1;
        $pagesize = (int)$param['pagesize'] ?? 10;

        $list = self::with('user')
            ->where($map)
            ->field('uid,loc_name,longitude,latitude,address')
            ->order('create_time desc')
            ->paginate($pagesize, false, ['page' => $page]);
        return ['code' => 200, 'msg' => '获取成功', 'data' => $list];
    }


    public function rebate($param)
    {
        try {

            if (!$param['sign']) {
                throw new Exception('参数错误');
            }
            $sign = $this->createSdkSign($param);
            if ($sign != $param['sign']) {
                throw new Exception('非法请求');
            }

            $uid = $param['uid']??0;
            $video_user = MemberModel::where(['id' => $uid])->find();
            $video_user = $video_user['nickName']??'无效用户';

            Db::startTrans();
            $loc = (new FishLoc())->where(['id' => $param['loc_id']])->find();
            if($loc['uid'] == $uid){
                return ['code' => 201, 'msg' => false, 'data' => ''];
            }
            if($loc['status'] == 0){
                throw new Exception('钓点已下架');
            }
            $param['uid'] = $loc['uid'];
            $param['loc_name'] = $loc['loc_name'];
            if (!$loc) {
                throw new Exception('钓点不存在');
            }

            //获取当前钓点需存到redis
//            $locNums = $this->redis->get('loc_id_'.$param['loc_id']);
//            if($locNums  != 2){
//                $this->redis->set('loc_id_'.$param['loc_id'], 2, $this->expireTime);
//                return ['code' => 201, 'msg' => false, 'data' => ''];
//            }


            //添加每天返现日志
            if (!(new RebateLog())->addLog($param, $video_user)) {
                throw new Exception('明细添加失败，请重新尝试');
            }

            //添加总播放次数
            if (!(new FishLoc())->where(['id' => $param['loc_id']])->setInc('video_num')) {
                throw new Exception('添加失败，请重新尝试');
            }

            Db::commit();

//            $this->redis->set('loc_id_'.$param['loc_id'], 1, $this->expireTime);
            return ['code' => 200, 'msg' => 'success', 'data' => ''];

        } catch (\Exception $e) {
            Db::rollback();
            Db::name('err_log')->insert(['uid' => $param['uid'],'loc_id' => $param['loc_id'],'msg' => $e->getMessage(),'create_time' => time()]);
            return ['code' => 201, 'msg' => $e->getMessage(), 'data' => ''];

        }

    }


    public function getLocVideoNum($params = array())
    {
        if (!$params['loc_id']) {
            return ['code' => 201, 'msg' => '缺少参数', 'data' => ''];
        }
        $page = $params['page'] ?? 1;
        $pagesize = (int)$params['pagesize'] ?? 10;
        $result = (new RebateLog())->where(['loc_id' => $params['loc_id']])
            ->field('day, COUNT(id) as video_num')
            ->group('day')
            ->order('create_time desc')
            ->paginate($pagesize, false, ['page' => $page]);

        return ['code' => 200, 'msg' => 'success', 'data' => $result];


    }


    public function createSdkSign($params)
    {
        unset($params['sign']);
        $secret = 'KfMTQ8EfqzFmv8L1K1TaxNds42yy4r3P';
        ksort($params);
        $str = http_build_query($params) . $secret;
        return strtolower(md5($str));
    }


    /**
     * Desc: 根据经纬度，半径范围获取附近
     * User: JamesLiu
     * Date: 2019/5/13
     * Time: 15:38
     * @param $longitude 经度
     * @param $latitude 纬度
     * @param $raidus 半径范围(单位：米)
     * @return array
     */
    public function getAround($longitude, $latitude, $raidus)
    {
        $PI = 3.14159265;
        $degree = (24901 * 1609) / 360.0;
        $dpmLat = 1 / $degree;
        $radiusLat = $dpmLat * $raidus;
        $minLat = $latitude - $radiusLat;
        $maxLat = $latitude + $radiusLat;
        $mpdLng = $degree * cos($latitude * ($PI / 180));
        $dpmLng = 1 / $mpdLng;
        $radiusLng = $dpmLng * $raidus;
        $minLng = $longitude - $radiusLng;
        $maxLng = $longitude + $radiusLng;
        return array('minLat' => $minLat, 'maxLat' => $maxLat, 'minLng' => $minLng, 'maxLng' => $maxLng);
    }


    public function delLoc($params)
    {
        if (!$params['loc_id']) {
            return ['code' => 201, 'msg' => '缺少参数', 'data' => ''];
        }

        $loc = (new FishLoc())->where(['id' => $params['loc_id']])->find();

        if ($loc->delete()) {
            return ['code' => 200, 'msg' => '删除成功', 'data' => ''];
        }

        return ['code' => 201, 'msg' => '删除失败', 'data' => ''];

    }


    public function updateLoc($params)
    {
        if (!$params['loc_id']) {
            return ['code' => 201, 'msg' => '缺少参数', 'data' => ''];
        }
        $loc = (new FishLoc())->where(['id' => $params['loc_id']])->find();

        if (!$loc) {
            return ['code' => 201, 'msg' => '钓点不存在', 'data' => ''];
        }

        $loc->loc_name = $params['loc_name'];
        $loc->longitude = $params['longitude'];
        $loc->latitude = $params['latitude'];
        $loc->address = $params['address'];

        if ($loc->save()) {
            return ['code' => 200, 'msg' => '修改成功', 'data' => ''];
        }

        return ['code' => 201, 'msg' => '修改失败', 'data' => ''];

    }
}
